import React from "react";
import { Button, Field, Form, Notify } from "react-vant";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { setUserAction } from "../../store/user";

const Index: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const onFinish = async (values: { username: string; password: string }) => {
    const resp = await axios.post("/api/login", values);
    const { code, data, message } = resp.data;
    if (code === 200) {
      Notify.show({ type: "success", message });
      dispatch(setUserAction({ isLogin: true, ...data }));
      navigate(-1);
    } else {
      Notify.show({ type: "danger", message });
    }
  };

  return (
    <div>
      <Form
        form={form}
        showValidateMessage={false}
        onFinish={onFinish}
        footer={
          <div style={{ margin: "16px 16px 0" }}>
            <Button round nativeType="submit" type="primary" block>
              提交
            </Button>
          </div>
        }
      >
        <Form.Item
          tooltip={{
            message:
              "A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.",
          }}
          intro="确保这是唯一的用户名"
          rules={[{ required: true, message: "请填写用户名" }]}
          name="username"
          label="用户名"
        >
          <Field placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          rules={[{ required: true, message: "请填写密码" }]}
          name="password"
          label="密码"
        >
          <Field placeholder="请输入密码" />
        </Form.Item>
      </Form>
			<h3></h3>
    </div>
  );
};

export default Index;
